package com.bianmaba.spring.security.basic.handler;

import com.bianmaba.spring.security.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: bianmaba-web-framework-extends
 * @description:
 * @author: Chenjiabin
 * @create: 2018-04-22 20:29
 **/
@ConditionalOnMissingBean({BianmabaAuthenticationSuccessHandler.class})
public class BianmabaAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(BianmabaSessionInformationExpiredStrategy.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        String requestType = request.getHeader("request_type");
        if ("ajax".equals(requestType)) {
            UserDetails principal = (UserDetails) authentication.getPrincipal();
            Map<String, Object> result = new HashMap<String, Object>(0);
            result.put("success", true);
            result.put("SecurityMessage", true);
            result.put("result", "用户登录成功");
            result.put("data", principal);
            ResponseUtil.writeJson(response, result, 200);
            LOGGER.debug(result.get("result").toString());
        } else {
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
